﻿using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using MySqlConnector;
using System.ComponentModel.DataAnnotations.Schema;
using efcore.core.Models;
using Microsoft.Extensions.Logging;
using 保存数据.Models;
using System.Diagnostics;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Options;
using System.Data.Common;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
    public DbSet<Person> Persons { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // modelBuilder.Entity<Blog>().HasQueryFilter(blog => blog.Url.Equals("feng"))
        modelBuilder.Entity<Blog>()
            .HasMany(e => e.Posts)
            .WithOne(e => e.Blog)
            .HasForeignKey("blog_id")
            .IsRequired(false);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        var mySqlConnection = new MySqlConnection("server=localhost;port=3306;database=test_asp;uid=root;pwd=rootroot;");
        options.UseMySql(mySqlConnection, MySqlServerVersion.LatestSupportedServerVersion)
        .LogTo(Console.WriteLine, LogLevel.Information);



        // options.AddInterceptors(new TaggedQueryCommandInterceptor());

    }
}

public class TaggedQueryCommandInterceptor : DbConnectionInterceptor
{
    public TaggedQueryCommandInterceptor()
    {
    }

    // public override InterceptionResult ConnectionOpening(DbConnection connection, ConnectionEventData eventData, InterceptionResult result)
    // {
    //   
    //
    //     return base.ConnectionOpening(connection, eventData, result);
    // }

    public override ValueTask<InterceptionResult> ConnectionOpeningAsync(DbConnection connection, ConnectionEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default)
    {
        connection.ConnectionString = "对应租户的连接字符串";

        return base.ConnectionOpeningAsync(connection, eventData, result, cancellationToken);
    }
}